from django.shortcuts import render,redirect
from django.views import View
from .forms import *
from django.http import HttpResponse,JsonResponse
from utils.code import gene_code
from utils.loadaddr import *
from cart.cartmanager import SessionCartManager

# Create your views here.

class FormTsetView(View):
    def get(self, request):
        u_form = RegisterForm()
        return render(request, 'form.html', {'u_form': u_form})

    def post(self, request):
        u_form = RegisterForm(request.POST)
        if u_form.is_valid():
            return HttpResponse('提交成功')
        else:
            str1 = ''
            for key, value in u_form.errors.items():
                str1 = str1+key+'=='+value+'<br>'
            return HttpResponse(1)


class RegisterView(View):
    def get(self, request):
        return render(request, 'register.html')

    def post(self, request):
        datas = request.POST.dict()
        register_form = RegisterForm(datas)
        if register_form.is_valid():
            user = User.register(**register_form.cleaned_data)
            request.session['user'] = user
            return HttpResponse('用户中心')
        else:
            return render(request, 'register.html', {'info': datas, 'errors': register_form.errors})


class UserCenterView(View):
    def get(self, request):
        user = request.session.get('user')
        return render(request, 'usercenter.html', {'user': user})


class LoginView(View):
    def get(self, request):
        redirect = request.GET.get('redirect', '')
        cartitems = request.GET.get('cartitems')
        return render(request, 'login.html', {'redirect': redirect, 'cartitems': cartitems})

    def post(self,requset):
        try:
            user = User.login(**requset.POST.dict())
            requset.session['user'] = user
            SessionCartManager(requset.session).migrateSession2DB()
            redir = requset.POST.get('redirect')
            if redir == 'cart':
                return redirect('/cart/cart.html')
            elif redir == 'order':
                return redirect('/order/?cartitems='+requset.POST.get('cartitems'))
            return redirect('/user/usercenter')
        except UserNotExistException:
            return render(requset, 'login.html')



class CodeView(View):
    def get(self, request):
        img, code = gene_code()
        request.session['code'] = code
        return HttpResponse(img, content_type='image/png')


class CheckCodeView(View):
    def get(self, request):
        code = request.GET.get('code', None)
        scode = request.session.get('code', '-1')
        result = (code == scode)
        return JsonResponse({'checkFlag': result})


class LogoutView(View):
    def post(self, request):
        if 'user' in request.session:
            del request.session['user']
        return JsonResponse({'result': True})


class AddressView(View):
    def get(self, request):
        provinces = get_provinces()
        user = request.session.get('user')
        addresses = []
        for address1 in Address.objects.filter(user=user):
            name = address1.uname
            phone = address1.phone
            list1 = address1.address.split(',')
            address = ''.join(list1[:-1])
            details = list1[-1]
            addresses.append({'name': name, 'phone': phone, 'address': address, 'details': details})
        return render(request, 'address.html', {'provinces': provinces, 'addresses': addresses})

    def post(self, request):
        type = request.POST.get('type')
        if type == '1':
            provinceId = request.POST.get('provinceId')
            citys, areas = get_citys_areas_by_provinceid(provinceId)
            return JsonResponse({'citys': citys, 'areas': areas})
        elif type == '2':
            cityid = request.POST.get('cityId')
            areas = get_areas_by_cityid(cityid)
            return JsonResponse({'areas': areas})
        elif type == '3':
            name = request.POST.get('name')
            phone = request.POST.get('phone')
            address = request.POST.get('address')
            user = request.session.get('user')
            if user.address_set.count() == 0:
                isdefault = True
            else:
                isdefault = False
            Address.objects.create(uname=name, phone=phone, address=address, user=user, isdefault=isdefault)

            html = '''<div class='dizhi'><p>姓名：{name}</p><p>手机号：{phone}</p><p>省市：{address}</p><p>详细地址：{details}</p></div>'''
            addresses = []
            for add in user.address_set.all():
                name = add.uname
                phone = add.phone
                list1 = add.address.split(',')
                address = ''.join(list1[:-1])
                details = list1[-1]
                addresses.append(html.format(name=name, phone=phone, address=address, details=details))
            return JsonResponse({'addresses': addresses})



